<?php

namespace app\admin\controller;

use app\BaseController;
use app\exam\model\Exam;
use app\exam\model\Question;
use think\facade\View;

class QuestionController extends BaseController
{
    /**
     * 题目列表页面
     */
    public function index()
    {
        $examId = input('exam_id');

        if (request()->isAjax()) {
            $page = input('page', 1);
            $limit = input('limit', 10);
            $title = input('title', '');
            $type = input('type', '');

            $where = [];
            if ($examId) {
                $where[] = ['exam_id', '=', $examId];
            }
            if ($title) {
                $where[] = ['title', 'like', '%' . $title . '%'];
            }
            if ($type !== '') {
                $where[] = ['type', '=', $type];
            }

            $list = Question::with(['exam'])
                ->where($where)
                ->order('exam_id desc, sort asc, id asc')
                ->paginate([
                    'list_rows' => $limit,
                    'page' => $page
                ]);

            return json([
                'code' => 0,
                'msg' => '',
                'count' => $list->total(),
                'data' => $list->items()
            ]);
        }

        // 获取考试列表
        $exams = Exam::where('status', 1)->select();
        View::assign('exams', $exams);

        return View::fetch();
    }

    /**
     * 添加题目页面
     */
    public function add()
    {
        if (request()->isPost()) {
            $data = input('post.');

            $validate = [
                'exam_id' => 'require|integer',
                'type' => 'require|in:1,2,3,4,5',
                'title' => 'require',
                'score' => 'require|float|gt:0'
            ];

            $result = $this->validate($data, $validate);
            if ($result !== true) {
                return json(['code' => 1, 'msg' => $result]);
            }

            // 检查考试是否存在
            $exam = Exam::find($data['exam_id']);
            if (!$exam) {
                return json(['code' => 1, 'msg' => '考试不存在']);
            }

            // 处理选项数据
            if (isset($data['options']) && is_array($data['options'])) {
                // 过滤空选项
                $data['options'] = array_filter($data['options'], function ($option) {
                    return !empty(trim($option));
                });
                $data['options'] = array_values($data['options']); // 重新索引
            }

            // 处理多选题答案
            if ($data['type'] == 2 && isset($data['correct_answer']) && is_array($data['correct_answer'])) {
                $data['correct_answer'] = implode(',', $data['correct_answer']);
            }

            $data['create_time'] = time();
            $data['update_time'] = time();

            $question = Question::create($data);

            return json(['code' => 0, 'msg' => '添加成功', 'data' => $question]);
        }

        // 获取考试列表
        $exams = Exam::where('status', 1)->select();
        View::assign('exams', $exams);

        return View::fetch();
    }

    /**
     * 编辑题目页面
     */
    public function edit()
    {
        $id = input('id');

        if (request()->isPost()) {
            $data = input('post.');

            $question = Question::find($id);
            if (!$question) {
                return json(['code' => 1, 'msg' => '题目不存在']);
            }

            // 处理选项数据
            if (isset($data['options']) && is_array($data['options'])) {
                $data['options'] = array_filter($data['options'], function ($option) {
                    return !empty(trim($option));
                });
                $data['options'] = array_values($data['options']);
            }

            // 处理多选题答案
            if ($data['type'] == 2 && isset($data['correct_answer']) && is_array($data['correct_answer'])) {
                $data['correct_answer'] = implode(',', $data['correct_answer']);
            }

            $data['update_time'] = time();
            $question->save($data);

            return json(['code' => 0, 'msg' => '更新成功']);
        }

        $question = Question::find($id);
        if (!$question) {
            $this->error('题目不存在');
        }

        // 处理多选题答案显示
        if ($question['type'] == 2 && $question['correct_answer']) {
            $question['correct_answer_array'] = explode(',', $question['correct_answer']);
        }

        // 获取考试列表
        $exams = Exam::where('status', 1)->select();

        View::assign([
            'question' => $question,
            'exams' => $exams
        ]);

        return View::fetch();
    }

    /**
     * 删除题目
     */
    public function delete()
    {
        $id = input('id');

        $question = Question::find($id);
        if (!$question) {
            return json(['code' => 1, 'msg' => '题目不存在']);
        }

        $question->delete();

        return json(['code' => 0, 'msg' => '删除成功']);
    }

    /**
     * 批量导入题目页面
     */
    public function import()
    {
        if (request()->isPost()) {
            $examId = input('exam_id');
            $questions = input('questions');

            if (!$examId || !$questions) {
                return json(['code' => 1, 'msg' => '参数错误']);
            }

            $exam = Exam::find($examId);
            if (!$exam) {
                return json(['code' => 1, 'msg' => '考试不存在']);
            }

            $successCount = 0;
            $errors = [];

            foreach ($questions as $index => $questionData) {
                try {
                    $questionData['exam_id'] = $examId;
                    $questionData['create_time'] = time();
                    $questionData['update_time'] = time();

                    Question::create($questionData);
                    $successCount++;
                } catch (\Exception $e) {
                    $errors[] = "第" . ($index + 1) . "题导入失败：" . $e->getMessage();
                }
            }

            return json([
                'code' => 0,
                'msg' => '导入完成',
                'data' => [
                    'success_count' => $successCount,
                    'error_count' => count($errors),
                    'errors' => $errors
                ]
            ]);
        }

        // 获取考试列表
        $exams = Exam::where('status', 1)->select();
        View::assign('exams', $exams);

        return View::fetch();
    }
}
